package com.zwcl.gdw.controller;

import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.common.core.utils.JsonUtils;
import com.zwcl.gdw.entity.UserVehicleInfo;
import com.zwcl.gdw.service.RcMatchCallService;
import com.zwcl.gdw.utils.UserVehicleVerifyUtil;
import com.zwcl.gdw.vo.GdwMatchVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.List;

@RestController
@RequestMapping("/rc")
@Slf4j
@Api(value = "match", tags = "人车匹配")
public class UserVehicleMatchController {

    @Autowired
    private RcMatchCallService rcMatchCallService;

    @PostMapping("/match")
    public GdwMatchVo userVehicleMatch(@RequestBody  UserVehicleInfo info){
        log.info("业务端接受参数：{}",info);
        long begin=System.currentTimeMillis();
        Boolean callSuccFlag=false;
        GdwMatchVo vo =null;
        String result=null;
        try {
            String plateNo =info.getPlateNo();
            String idNum = info.getIdNum();
            String userName = info.getUserName();
            //前两个参数是固定的，后两个参数是行云提供的账户和授权码。临时写成字符串传入，最好改造一下
            String service = "ETCUSER";//固定
            String subService = "USERVEHICLEVERIFY";//固定
            String client = "000042";//行云发放
            String code = "CBCC6ee1n0";//行云发放
            //内容自己构建
            String contentTemplate = "'{'\"plateNo\":\"{0}\",\"idNum\":\"{1}\",\"userName\":\"{2}\"'}'";
            String content = MessageFormat.format(contentTemplate, plateNo,idNum,userName);

            List<String> parameters = UserVehicleVerifyUtil.prepare(service,subService,client,code);
            result = UserVehicleVerifyUtil.send(parameters.get(0),content,parameters.get(1),parameters.get(2),parameters.get(3));
            //result= "{\"info\":\"成功\",\"receiveTime\":\"2021-03-17T13:35:26\",\"result_code\":\"1\"}";
            log.info("调用返回结果：{}",result);
            callSuccFlag=true;
            vo = JsonUtils.jsonToPojo(result,GdwMatchVo.class);
            return vo;
        }catch (Exception ex){
            log.error("调用失败，{}",ex);
            callSuccFlag=false;
            throw new BusinessException("调用失败，无匹配结果");
        }finally {
            //异步保存结果
            long timeValue = System.currentTimeMillis() - begin;
            rcMatchCallService.ayncSaveRcMatchCall(vo,result,info,callSuccFlag,timeValue);
        }
    }
}
